package cn.edu.scau.cmi.lvmingyan.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Action{
	Connection connection=null;
	
	public void  init(String passion) {//初始化Driver和连接数据库
	try {//初始化Driver
		Class.forName("com.mysql.jdbc.Driver");
		System.out.println("success loading mysql");
	}catch(Exception e) {
		System.out.println("Error loading");
		e.printStackTrace();
	}
	
	try {//连接数据库
		 connection=DriverManager.getConnection
				("jdbc:mysql://localhost:3306/mysql","root",passion);
		System.out.println("success connect");			
	}catch(Exception e) {
		System.out.println("Error connet");
		e.printStackTrace();
	}
}

	
	public void selectAll()
	{
		try {
			Statement statement =connection.createStatement();
			ResultSet result=statement.executeQuery("select * from student");
			while(result.next()) {
				System.out.println(result.getInt("id")+" "+result.getString("name"));  
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public int insertStu(int id,String name) {
		
		try {
		    
		    /*Statement statement=connection.createStatement();
		    statement.executeUpdate("insert into student values(9,'岑参')");*/
		    
			PreparedStatement pstatement =null;
			pstatement =connection.prepareStatement("insert into student values(?,?);");
			for(int i=0;i<10;i++)
			{
				pstatement.setInt(1,id+i );
			pstatement.setString(2,name );
			pstatement.execute();
			}
			
			
			System.out.println("插入成功");
			return 1;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("插入失败");
			return 0;
		}
		
	}
	
}
